#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>
#include <QDesktopServices>
#include <QTextCursor>
#include <QMessageBox>
#include <QRegularExpression>
#include <QFile>
#include <QApplication>
#include <QSettings>
#include <QDir>
#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QScrollArea>
#include <QCheckBox>
#include <QPushButton>
#include <QLabel>
#include <QFont>
#include <QMap>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    // 加载样式表
    loadStyleSheet();
    
    initArgument();
    initObjects();
    initWidgets();
    initSignals();
    loadLastPaths();
    updateCommandDisplay();

    QButtonGroup *btGr = new QButtonGroup;
    btGr->addButton(ui->CB_QML);
    btGr->addButton(ui->CB_Win);
    btGr->setExclusive(true);
    ui->CB_Win->setChecked(true);
    
    // 默认Widget模式下隐藏qmldir相关控件
    ui->qmldir->setVisible(false);
    ui->TB_qmldir->setVisible(false);
    ui->label->setVisible(false);
}

MainWindow::~MainWindow()
{
//    workThread->quit();
//    workThread->wait();
    delete ui;
}

void MainWindow::setCommand(QString data)
{
    temp = data;
    command = temp + "/bin/windeployqt.exe";
    ui->le_dep->setText(command);
}


void MainWindow::on_toolButton_clicked()
{
    // 使用上次保存的路径作为默认路径
    QSettings settings("QtDeploy", "PathMemory");
    QString defaultPath = settings.value("lastAppPathAndName", "/home/test.exe").toString();
    
    appPathAndName = QFileDialog::getOpenFileName(this, tr("Save File"),
                                           defaultPath,
                                           tr("APP (*.exe *.EXE);;All Files (*)"));
    
    if (!appPathAndName.isEmpty()) {
        exeName=appPathAndName.section('/', -1);
        // 如果文件没有后缀，section('.',0,0)会返回整个文件名，这是正确的
        appName = exeName.section('.',0,0);
        // 如果没有找到点号，说明文件没有后缀，直接使用文件名
        if (appName.isEmpty()) {
            appName = exeName;
        }
        appPath = appPathAndName.left(appPathAndName.lastIndexOf("/"));
        ui->AppPath->setText(appPath);
        ui->appName->setText(appName);
        ui->Run->setDisabled(false);
        
        // 重新计算Qt路径以应用架构检测
        command = readSystemEnv();
        ui->statusBar->showMessage("当前读取到的Qt路径: " + command);
        
        // 保存新选择的路径
        saveLastPaths();
    }
}


void MainWindow::on_Run_clicked()
{
    setBtnVisible(false);
    modifyArument();
    progress->runApplication(command,argument);
    emit StartProcess();
}


void MainWindow::Command_out(QString strDisplay)
{
    ui->textBrowser->setText(strDisplay);
}

void MainWindow::initSignals()
{
    QObject::connect(progress,SIGNAL(CommandOutput(QString)),this,SLOT(Command_out(QString)),Qt::QueuedConnection);
    QObject::connect(progress,SIGNAL(finished(int)),this,SLOT(ProcessFinished(int)),Qt::DirectConnection);
    QObject::connect(this,SIGNAL(StartProcess(void)),progress,SLOT(startProcess(void)),Qt::DirectConnection);
    QObject::connect(progress,SIGNAL(processFinished(int)),this,SLOT(ProcessFinished(int)),Qt::QueuedConnection);
}

void MainWindow::initWidgets()
{
    ui->textBrowser->moveCursor(QTextCursor::End);
    setBtnVisible(false);
}

void MainWindow::initObjects()
{
    //workThread = new QThread(this);
    progress = new MyProcess(this);
//    workThread->start();
//    progress->moveToThread(workThread);
}

void MainWindow::initArgument()
{
    command = readSystemEnv();
    // 在状态栏显示读取到的Qt路径
    ui->statusBar->showMessage("当前读取到的Qt路径: " + command);
}

void MainWindow::loadStyleSheet()
{
    QFile file(":/styles.qss");
    if (!file.exists()) {
        // 如果资源文件不存在，尝试从文件系统加载
        file.setFileName("styles.qss");
    }
    
    if (file.open(QFile::ReadOnly | QFile::Text)) {
        QString styleSheet = QLatin1String(file.readAll());
        qApp->setStyleSheet(styleSheet);
        file.close();
    } else {
        qDebug() << "无法加载样式表文件";
    }
}

void MainWindow::modifyArument()
{
    argument.clear();
    

    if(ui->CB_WebKit->isChecked())
    {
        argument.append("--webkit2");
    }
    if(ui->CB_3D->isChecked())
    {
        argument.append("--quick");
    }
    if(ui->CB_Release->isChecked())
    {
        argument.append("--release");
    }
    if(ui->CB_Runtime->isChecked())
    {
        argument.append("--compiler-runtime");
    }

    // 先添加所有选项参数
    // 只有在QML模式下才添加qmldir参数
    if(ui->CB_QML->isChecked() && !qmlPath.isEmpty())
    {
        argument.append("--qmldir");
        argument.append(qmlPath);
    }
    
    // 添加libdir参数
    if(!ui->le_libdir->text().isEmpty())
    {
        argument.append("--libdir");
        argument.append(ui->le_libdir->text());
    }
    
    // 添加plugindir参数
    if(!ui->le_plugindir->text().isEmpty())
    {
        argument.append("--plugindir");
        argument.append(ui->le_plugindir->text());
    }
    
    // 添加translations参数
    if(!ui->le_translations->text().isEmpty())
    {
        argument.append("--translations");
        argument.append(ui->le_translations->text());
    }
    
    // 最后添加目标应用程序路径
    argument.append(appPathAndName);
    
    updateCommandDisplay();
}

void MainWindow::setBtnVisible(bool data)
{
    ui->Run->setEnabled(data);
}

QString MainWindow::readConfigFile()
{
    QString configPath = QDir::currentPath() + "/conf/conf.ini";
    qDebug() << "Config file path:" << configPath;
    QSettings settings(configPath, QSettings::IniFormat);
    QString qtPath = settings.value("QTDIR/PATH", "").toString();
    qDebug() << "Read QTDIR from config:" << qtPath;
    qtPath.replace(QRegularExpression("\\\\"), "/");
    return qtPath;
}

QString MainWindow::readSystemEnv()
{
    QString path = readConfigFile();
    if(path.isEmpty()){
        path = QProcessEnvironment::systemEnvironment().value("QTDIR");
        path.replace(QRegularExpression("\\\\"), "/");
        if(path == ""){
            path = temp;
        }
    }
    
    // 智能架构检测和路径切换
    // 如果配置的是64位路径但目标程序是32位，自动切换到32位路径
    if (path.contains("mingw81_64") && !appPathAndName.isEmpty()) {
        // 检测目标程序架构
        QString targetArch = detectExecutableArchitecture(appPathAndName);
        if (targetArch == "32bit") {
            // 自动切换到32位Qt路径
            path = path.replace("mingw81_64", "mingw81_32");
            qDebug() << "检测到32位目标程序，自动切换到32位Qt路径:" << path;
        }
    }
    // 如果配置的是32位路径但目标程序是64位，自动切换到64位路径
    else if (path.contains("mingw81_32") && !appPathAndName.isEmpty()) {
        QString targetArch = detectExecutableArchitecture(appPathAndName);
        if (targetArch == "64bit") {
            // 自动切换到64位Qt路径
            path = path.replace("mingw81_32", "mingw81_64");
            qDebug() << "检测到64位目标程序，自动切换到64位Qt路径:" << path;
        }
    }
    
    path+="/bin/windeployqt.exe";
    return path;
}

void MainWindow::on_qmldir_textChanged(const QString &arg1)
{
    qDebug()<<arg1;
    tempArgu.clear();
    qmlPath = arg1;
    tempArgu.append("--qmldir");
    tempArgu.append(arg1);
}

void MainWindow::ProcessFinished(int id)
{
    if(0 == id){
        progress->stop();
        setBtnVisible(true);
        ui->textBrowser->append("\n");
        ui->textBrowser->append("\n");
        ui->textBrowser->append("\n");
        ui->textBrowser->append("\n");
        ui->textBrowser->append("=== 打包成功完成! ===");
        ui->textBrowser->moveCursor(QTextCursor::End);
        ui->OpenDir->setEnabled(true);
        
        // 更新状态栏
        ui->statusBar->showMessage("Qt应用打包成功完成！", 10000);
        
        // 显示成功消息框
        QString appPath = ui->AppPath->text();
        QString outputDir = QFileInfo(appPath).absolutePath();
        
        QMessageBox msgBox(this);
        msgBox.setWindowTitle("打包完成");
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setText("Qt应用打包成功完成！");
        msgBox.setInformativeText(QString("应用程序: %1\n输出目录: %2\n\n所有依赖文件已成功复制到应用程序目录。\n您可以点击'打开目录'按钮查看结果。").arg(QFileInfo(appPath).fileName(), outputDir));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.exec();
        
        // 播放系统提示音
        QApplication::beep();
        
    }else{
        progress->stop();
        setBtnVisible(true);
        ui->textBrowser->append("\n");
        ui->textBrowser->append("=== 打包过程出现错误! ===");
        ui->textBrowser->moveCursor(QTextCursor::End);
        
        // 更新状态栏
        ui->statusBar->showMessage("打包过程出现错误，请检查日志信息。", 10000);
        
        // 显示错误消息框
        QMessageBox::warning(this, "打包失败", 
            "打包过程中出现错误，请检查：\n\n"
            "1. 目标应用程序是否存在\n"
            "2. Qt路径配置是否正确\n"
            "3. 是否有足够的磁盘空间\n"
            "4. 查看详细日志信息以了解具体错误");
        
        qDebug()<<__FUNCTION__<<"--->CrashExit";
    }

}

void MainWindow::on_TB_qmldir_clicked()
{
    // 使用上次保存的QML路径作为默认路径
    QSettings settings("QtDeploy", "PathMemory");
    QString defaultQmlPath = settings.value("lastQmlPath", "/home").toString();
    
    qmlPath = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                             defaultQmlPath,
                                                             QFileDialog::ShowDirsOnly
                                                             | QFileDialog::DontResolveSymlinks);
    
    if (!qmlPath.isEmpty()) {
        qDebug()<<qmlPath;
        ui->qmldir->setText(qmlPath);
        
        // 保存新选择的路径
        saveLastPaths();
    }
}

void MainWindow::on_CB_QML_toggled(bool checked)
{
    // QML模式下显示qmldir相关控件
    ui->qmldir->setVisible(checked);
    ui->TB_qmldir->setVisible(checked);
    // 同时显示/隐藏qmldir标签
    ui->label->setVisible(checked);
    modifyArument();
}

/**
 * @brief 处理Widget模式单选按钮切换事件
 * @param checked 是否选中Widget模式
 */
void MainWindow::on_CB_Win_toggled(bool checked)
{
    // Widget模式下隐藏qmldir相关控件
    ui->qmldir->setVisible(!checked);
    ui->TB_qmldir->setVisible(!checked);
    // 同时显示/隐藏qmldir标签
    ui->label->setVisible(!checked);
    modifyArument();
}


void MainWindow::on_OpenDir_clicked()
{
    QDesktopServices::openUrl(QUrl(appPath, QUrl::TolerantMode));
}

void MainWindow::on_Btn_clear_clicked()
{
    ui->textBrowser->clear();
}

void MainWindow::on_action_triggered()
{
    about.show();
}

void MainWindow::on_actionScanQt_triggered()
{
    // 创建Qt扫描器对话框
    QtScanner scanner(this);
    
    // 显示对话框并等待用户选择
    if (scanner.exec() == QDialog::Accepted) {
        QString selectedQtPath = scanner.getSelectedQtPath();
        
        if (!selectedQtPath.isEmpty()) {
            // 更新配置文件
            QString configPath = QDir::currentPath() + "/conf/conf.ini";
            QSettings settings(configPath, QSettings::IniFormat);
            settings.setValue("QTDIR/PATH", selectedQtPath);
            settings.sync();
            
            // 更新当前命令
            command = selectedQtPath + "/bin/windeployqt.exe";
            ui->le_dep->setText(command);
            
            // 更新状态栏（持续显示5秒）
            ui->statusBar->showMessage("Qt路径已成功更新: " + selectedQtPath, 5000);
            
            // 更新命令显示
            updateCommandDisplay();
            
            // 显示成功消息框
            QMessageBox::information(this, "Qt路径更新成功", 
                QString("Qt路径已成功更新为:\n%1\n\n配置文件已保存，可以开始使用新的Qt环境进行打包。").arg(selectedQtPath));
            
            qDebug() << "Qt路径已更新为:" << selectedQtPath;
        }
    } else {
        // 用户取消了选择
        ui->statusBar->showMessage("Qt路径扫描已取消", 3000);
    }
}

void MainWindow::on_AppPath_textChanged(const QString &arg1)
{
    // arg1是路径，需要与可执行文件名组合
    appPath = arg1;
    if (!appName.isEmpty()) {
        // 检查appName是否已经包含扩展名
        QString fileName = appName;
        if (!fileName.endsWith(".exe", Qt::CaseInsensitive)) {
            fileName += ".exe";
        }
        appPathAndName = appPath + "/" + fileName;
        
        // 重新计算Qt路径以应用架构检测
        command = readSystemEnv();
        ui->statusBar->showMessage("当前读取到的Qt路径: " + command);
    }
    modifyArument();
    setBtnVisible(true);
}

void MainWindow::on_actionQTDIR_triggered()
{
    QMessageBox::information(this, "QTDIR说明", "本文件夹下的conf目录conf.ini文件修改QTDIR", QMessageBox::Yes , QMessageBox::Yes);
}

/**
 * @brief 选择库文件输出目录
 */
void MainWindow::on_TB_libdir_clicked()
{
    // 使用上次保存的路径作为默认路径
    QSettings settings("QtDeploy", "PathMemory");
    QString defaultPath = settings.value("lastLibDir", QDir::homePath()).toString();
    
    QString libDir = QFileDialog::getExistingDirectory(this, tr("选择库文件输出目录"),
                                                      defaultPath,
                                                      QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    
    if (!libDir.isEmpty()) {
        ui->le_libdir->setText(libDir);
        // 保存路径
        settings.setValue("lastLibDir", libDir);
        // 更新命令显示
        updateCommandDisplay();
    }
}

/**
 * @brief 选择插件输出目录
 */
void MainWindow::on_TB_plugindir_clicked()
{
    // 使用上次保存的路径作为默认路径
    QSettings settings("QtDeploy", "PathMemory");
    QString defaultPath = settings.value("lastPluginDir", QDir::homePath()).toString();
    
    QString pluginDir = QFileDialog::getExistingDirectory(this, tr("选择插件输出目录"),
                                                         defaultPath,
                                                         QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    
    if (!pluginDir.isEmpty()) {
        ui->le_plugindir->setText(pluginDir);
        // 保存路径
        settings.setValue("lastPluginDir", pluginDir);
        // 更新命令显示
        updateCommandDisplay();
    }
 }
 
 /**
  * @brief libdir文本变化时更新命令显示
  */
 void MainWindow::on_le_libdir_textChanged(const QString &arg1)
 {
     Q_UNUSED(arg1)
     if (!appPathAndName.isEmpty()) {
         modifyArument();
     }
 }
 
 /**
  * @brief plugindir文本变化时更新命令显示
  */
 void MainWindow::on_le_plugindir_textChanged(const QString &arg1)
 {
     Q_UNUSED(arg1)
     if (!appPathAndName.isEmpty()) {
         modifyArument();
     }
 }
 
 /**
  * @brief translations文本变化时更新命令显示
  */
 void MainWindow::on_le_translations_textChanged(const QString &arg1)
 {
     Q_UNUSED(arg1)
     if (!appPathAndName.isEmpty()) {
         modifyArument();
     }
 }

 /**
  * @brief 弹出多选语言对话框
  */
 void MainWindow::on_tb_popSelect_clicked()
 {
     // 创建语言选择对话框
     QDialog *languageDialog = new QDialog(this);
     languageDialog->setWindowTitle("选择翻译语言");
     languageDialog->setModal(true);
     languageDialog->resize(400, 500);
     
     // 创建布局
     QVBoxLayout *mainLayout = new QVBoxLayout(languageDialog);
     
     // 添加说明标签
     QLabel *infoLabel = new QLabel("请选择需要的翻译语言（可多选）:", languageDialog);
     infoLabel->setFont(QFont("", 10));
     mainLayout->addWidget(infoLabel);
     
     // 创建滚动区域
     QScrollArea *scrollArea = new QScrollArea(languageDialog);
     QWidget *scrollWidget = new QWidget();
     QVBoxLayout *scrollLayout = new QVBoxLayout(scrollWidget);
     
     // 定义可用的语言列表
     QStringList availableLanguages = {
         "zh_CN", "zh_TW", "en_US", "ja_JP", "ko_KR",
         "de_DE", "fr_FR", "es_ES", "it_IT", "pt_BR",
         "ru_RU", "ar_SA", "hi_IN", "th_TH", "vi_VN",
         "nl_NL", "sv_SE", "da_DK", "no_NO", "fi_FI",
         "pl_PL", "cs_CZ", "hu_HU", "sk_SK", "bg_BG",
         "hr_HR", "sl_SI", "et_EE", "lv_LV", "lt_LT",
         "uk_UA", "be_BY", "mk_MK", "sq_AL", "sr_RS",
         "ro_RO", "el_GR", "tr_TR", "he_IL", "fa_IR"
     };
     
     // 语言名称映射
     QMap<QString, QString> languageNames = {
         {"zh_CN", "简体中文 (zh_CN)"},
         {"zh_TW", "繁体中文 (zh_TW)"},
         {"en_US", "English (en_US)"},
         {"ja_JP", "日本語 (ja_JP)"},
         {"ko_KR", "한국어 (ko_KR)"},
         {"de_DE", "Deutsch (de_DE)"},
         {"fr_FR", "Français (fr_FR)"},
         {"es_ES", "Español (es_ES)"},
         {"it_IT", "Italiano (it_IT)"},
         {"pt_BR", "Português (pt_BR)"},
         {"ru_RU", "Русский (ru_RU)"},
         {"ar_SA", "العربية (ar_SA)"},
         {"hi_IN", "हिन्दी (hi_IN)"},
         {"th_TH", "ไทย (th_TH)"},
         {"vi_VN", "Tiếng Việt (vi_VN)"},
         {"nl_NL", "Nederlands (nl_NL)"},
         {"sv_SE", "Svenska (sv_SE)"},
         {"da_DK", "Dansk (da_DK)"},
         {"no_NO", "Norsk (no_NO)"},
         {"fi_FI", "Suomi (fi_FI)"},
         {"pl_PL", "Polski (pl_PL)"},
         {"cs_CZ", "Čeština (cs_CZ)"},
         {"hu_HU", "Magyar (hu_HU)"},
         {"sk_SK", "Slovenčina (sk_SK)"},
         {"bg_BG", "Български (bg_BG)"},
         {"hr_HR", "Hrvatski (hr_HR)"},
         {"sl_SI", "Slovenščina (sl_SI)"},
         {"et_EE", "Eesti (et_EE)"},
         {"lv_LV", "Latviešu (lv_LV)"},
         {"lt_LT", "Lietuvių (lt_LT)"},
         {"uk_UA", "Українська (uk_UA)"},
         {"be_BY", "Беларуская (be_BY)"},
         {"mk_MK", "Македонски (mk_MK)"},
         {"sq_AL", "Shqip (sq_AL)"},
         {"sr_RS", "Српски (sr_RS)"},
         {"ro_RO", "Română (ro_RO)"},
         {"el_GR", "Ελληνικά (el_GR)"},
         {"tr_TR", "Türkçe (tr_TR)"},
         {"he_IL", "עברית (he_IL)"},
         {"fa_IR", "فارسی (fa_IR)"}
     };
     
     // 获取当前已选择的语言
     QString currentText = ui->le_translations->text().trimmed();
     QStringList selectedLanguages;
     if (!currentText.isEmpty()) {
         selectedLanguages = currentText.split(",", Qt::SkipEmptyParts);
         for (int i = 0; i < selectedLanguages.size(); ++i) {
             selectedLanguages[i] = selectedLanguages[i].trimmed();
         }
     }
     
     // 创建复选框列表
     QList<QCheckBox*> checkBoxes;
     for (const QString &langCode : availableLanguages) {
         QCheckBox *checkBox = new QCheckBox(languageNames.value(langCode, langCode), scrollWidget);
         checkBox->setObjectName(langCode);
         
         // 如果当前语言已被选中，则勾选复选框
         if (selectedLanguages.contains(langCode)) {
             checkBox->setChecked(true);
         }
         
         checkBoxes.append(checkBox);
         scrollLayout->addWidget(checkBox);
     }
     
     scrollWidget->setLayout(scrollLayout);
     scrollArea->setWidget(scrollWidget);
     scrollArea->setWidgetResizable(true);
     mainLayout->addWidget(scrollArea);
     
     // 添加全选/全不选按钮
     QHBoxLayout *selectAllLayout = new QHBoxLayout();
     QPushButton *selectAllBtn = new QPushButton("全选", languageDialog);
     QPushButton *selectNoneBtn = new QPushButton("全不选", languageDialog);
     
     connect(selectAllBtn, &QPushButton::clicked, [checkBoxes]() {
         for (QCheckBox *cb : checkBoxes) {
             cb->setChecked(true);
         }
     });
     
     connect(selectNoneBtn, &QPushButton::clicked, [checkBoxes]() {
         for (QCheckBox *cb : checkBoxes) {
             cb->setChecked(false);
         }
     });
     
     selectAllLayout->addWidget(selectAllBtn);
     selectAllLayout->addWidget(selectNoneBtn);
     selectAllLayout->addStretch();
     mainLayout->addLayout(selectAllLayout);
     
     // 添加确定和取消按钮
     QHBoxLayout *buttonLayout = new QHBoxLayout();
     QPushButton *okBtn = new QPushButton("确定", languageDialog);
     QPushButton *cancelBtn = new QPushButton("取消", languageDialog);
     
     buttonLayout->addStretch();
     buttonLayout->addWidget(okBtn);
     buttonLayout->addWidget(cancelBtn);
     mainLayout->addLayout(buttonLayout);
     
     // 连接按钮信号
     connect(okBtn, &QPushButton::clicked, languageDialog, &QDialog::accept);
     connect(cancelBtn, &QPushButton::clicked, languageDialog, &QDialog::reject);
     
     // 显示对话框
     if (languageDialog->exec() == QDialog::Accepted) {
         // 收集选中的语言
         QStringList selectedLangs;
         for (QCheckBox *cb : checkBoxes) {
             if (cb->isChecked()) {
                 selectedLangs.append(cb->objectName());
             }
         }
         
         // 更新输入框
         ui->le_translations->setText(selectedLangs.join(","));
         
         // 更新命令显示
         updateCommandDisplay();
     }
     
     // 清理
     languageDialog->deleteLater();
 }
 
 void MainWindow::saveLastPaths()
{
    QSettings settings("QtDeploy", "PathMemory");
    settings.setValue("lastAppPath", appPath);
    settings.setValue("lastAppPathAndName", appPathAndName);
    settings.setValue("lastQmlPath", qmlPath);
    settings.setValue("lastLibDir", ui->le_libdir->text());
    settings.setValue("lastPluginDir", ui->le_plugindir->text());
    settings.setValue("lastTranslations", ui->le_translations->text());
}

void MainWindow::updateCommandDisplay()
{
    QString fullCommand = command;
    for (const QString &arg : argument) {
        fullCommand += " " + arg;
    }
    ui->commandDisplay->setPlainText(fullCommand);
}

void MainWindow::loadLastPaths()
{
    QSettings settings("QtDeploy", "PathMemory");
    QString lastAppPath = settings.value("lastAppPath", "/home").toString();
    QString lastAppPathAndName = settings.value("lastAppPathAndName", "/home/test.exe").toString();
    QString lastQmlPath = settings.value("lastQmlPath", "/home").toString();
    QString lastLibDir = settings.value("lastLibDir", "").toString();
    QString lastPluginDir = settings.value("lastPluginDir", "").toString();
    QString lastTranslations = settings.value("lastTranslations", "").toString();
    
    // 如果保存的路径存在，则使用保存的路径
    if (!lastAppPathAndName.isEmpty() && QFile::exists(lastAppPathAndName)) {
        appPathAndName = lastAppPathAndName;
        exeName = appPathAndName.section('/', -1);
        appName = exeName.section('.', 0, 0);
        appPath = appPathAndName.left(appPathAndName.lastIndexOf("/"));
        ui->AppPath->setText(appPath);
        ui->appName->setText(appName);
        ui->Run->setDisabled(false);
    }
    
    if (!lastQmlPath.isEmpty() && QDir(lastQmlPath).exists()) {
        qmlPath = lastQmlPath;
        ui->qmldir->setText(qmlPath);
    }
    
    // 加载新选项的保存值
    if (!lastLibDir.isEmpty()) {
        ui->le_libdir->setText(lastLibDir);
    }
    
    if (!lastPluginDir.isEmpty()) {
        ui->le_plugindir->setText(lastPluginDir);
    }
    
    if (!lastTranslations.isEmpty()) {
        ui->le_translations->setText(lastTranslations);
    }
}

/**
 * 检测可执行文件的架构（32位或64位）
 * 通过读取PE文件头中的Machine字段来判断
 */
QString MainWindow::detectExecutableArchitecture(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "无法打开文件:" << filePath;
        return "unknown";
    }
    
    // 读取DOS头
    QByteArray dosHeader = file.read(64);
    if (dosHeader.size() < 64) {
        qDebug() << "文件太小，不是有效的PE文件";
        return "unknown";
    }
    
    // 检查DOS签名 "MZ"
    if (dosHeader[0] != 'M' || dosHeader[1] != 'Z') {
        qDebug() << "不是有效的PE文件（缺少MZ签名）";
        return "unknown";
    }
    
    // 获取PE头偏移量（在DOS头的0x3C位置）
    quint32 peOffset = *reinterpret_cast<const quint32*>(dosHeader.data() + 0x3C);
    
    // 跳转到PE头
    if (!file.seek(peOffset)) {
        qDebug() << "无法跳转到PE头位置";
        return "unknown";
    }
    
    // 读取PE签名和文件头
    QByteArray peHeader = file.read(24); // PE签名(4) + 文件头(20)
    if (peHeader.size() < 24) {
        qDebug() << "无法读取PE头";
        return "unknown";
    }
    

    // 获取Machine字段（在PE签名后的第一个字段）
    quint16 machine = *reinterpret_cast<const quint16*>(peHeader.data() + 4);
    
    // 根据Machine字段判断架构
    switch (machine) {
        case 0x014c: // IMAGE_FILE_MACHINE_I386
            qDebug() << "检测到32位程序:" << filePath;
            return "32bit";
        case 0x8664: // IMAGE_FILE_MACHINE_AMD64
            qDebug() << "检测到64位程序:" << filePath;
            return "64bit";
        default:
            qDebug() << "未知架构，Machine值:" << QString::number(machine, 16);
            return "unknown";
    }
}

